package com.example.jiangkt.ergongyi.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSONObject;
import com.example.jiangkt.ergongyi.R;
import com.example.jiangkt.ergongyi.adapter.RoomListAdapter;
import com.example.jiangkt.ergongyi.entity.RoomInfo;
import com.example.jiangkt.ergongyi.util.AlertShow;
import com.example.jiangkt.ergongyi.util.CustomAction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoActivity extends Activity implements View.OnClickListener {
    private TextView tv_username;
    private TextView tv_key;
    private ToggleButton tb_music;
    private Button bt_scratch_card;
    private String userInfo;
    private JSONObject jsonObject;
    private NumberPicker lower_chip;
    private NumberPicker upper_chip;
    private NumberPicker user_limit;
    private LinearLayout tl_chip_limit;
    private int minDefaultValue;
    private int maxDefaultValue;
    private int userLimit;
    private Intent intent;
    private UserInfoReceiver userReceiver;
    private ListView room_list;
    private SwipeRefreshLayout search_room_list;
    private Intent musicIntent;
    private String roomList;
    private AlertDialog createDialog;
    private AlertDialog joinDialog;
    private String userId;
    private String userName;
    private String roomKey;
    private ImageView create_room;
    private ImageView join_room;
    private TextView createWarn;
    private SearchView search_room;
    private TextView joinWarn;
    private ImageView iv_create_cancel;
    private ImageView iv_join_cancel;
    private Button bt_edit_room;
    private ImageView iv_create_down;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        this.init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (joinDialog!=null){
            joinDialog.dismiss();
        }
        if (createDialog!=null){
            createDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (joinDialog!=null){
            joinDialog.dismiss();
        }
        if (createDialog!=null){
            createDialog.dismiss();
        }
        unregisterReceiver(userReceiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Map<String, Object> map = new HashMap<>();
            map.put("reqType", "exitReq");
            intent.putExtra("request", JSONObject.toJSON(map).toString());
            sendBroadcast(intent);
            musicIntent.putExtra("musicStatus", false);
            sendBroadcast(musicIntent);
            finish();
        }
        return false;
    }

    private void init() {
//        tb_music = findViewById(R.id.ui_tb_music);
//        tb_music.setChecked(false);
        create_room = findViewById(R.id.ui_bt_create);
        create_room.setOnClickListener(this);
        join_room = findViewById(R.id.ui_bt_join);
        join_room.setOnClickListener(this);
        tv_username = findViewById(R.id.ui_tv_username);
        tv_key = findViewById(R.id.ui_tv_key);

//        bt_scratch_card = findViewById(R.id.bt_scratch_card);

        Intent getIntent = getIntent();
//        userInfo = (String) getIntent.getSerializableExtra("userInfo");毕设暂时不需要

        //刚开始就设置发送广播的action，因为该activity使用的action是一致的除了SOUND_ACTION
        intent = new Intent(CustomAction.SERVICE_ACTION);
        musicIntent = new Intent(CustomAction.SOUND_ACTION);

        IntentFilter filter = new IntentFilter(CustomAction.USER_ACTION);
        userReceiver = new UserInfoReceiver();
        registerReceiver(userReceiver, filter);

        //毕设暂时不需要
        /*jsonObject = JSONObject.parseObject(userInfo);
        userId = jsonObject.getString("userId");
        userName = jsonObject.getString("userName");
        roomKey = jsonObject.getString("roomKey");*/
        userId = (String) getIntent.getSerializableExtra("userId");
        userName = (String) getIntent.getSerializableExtra("userName");
        roomKey = (String) getIntent.getSerializableExtra("roomKey");

        tv_username.setText(userName);
        tv_key.setText(roomKey);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ui_bt_create:
                /*create_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.in_anim));
                create_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.out_anim));*/

                this.initLimit();

                createDialog = new AlertDialog.Builder(this)
                        .setView(tl_chip_limit)
                        .create();
                createDialog.show();
                break;
            case R.id.bt_edit_room:
                HashMap<Object, Object> crrMap = new HashMap<>();
                crrMap.put("reqType", "createRoomReq");
                crrMap.put("userId", userId);//jsonObject.getString("userId")
                crrMap.put("upperChip", maxDefaultValue);
                crrMap.put("lowerChip", minDefaultValue);
                crrMap.put("userLimit", userLimit);

                intent.putExtra("request", JSONObject.toJSON(crrMap).toString());
                sendBroadcast(intent);
//                createDialog.dismiss();关闭就看不了错误提示
                break;
            case R.id.iv_create_cancel:
                createDialog.cancel();
                break;
            case R.id.ui_bt_join:
                AlertShow.dialog = ProgressDialog.show(this, null, "获取房间中...");

                /*join_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.in_anim));
                join_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.out_anim));*/

                Map<Object, Object> grlMap = new HashMap<>();
                grlMap.put("reqType", "getRoomListReq");
                grlMap.put("filterRoom", "");
                intent.putExtra("request", JSONObject.toJSON(grlMap).toString());
                sendBroadcast(intent);


                search_room_list = (SwipeRefreshLayout) UserInfoActivity.this.getLayoutInflater().inflate(R.layout.search_room_list, null);
                iv_join_cancel = search_room_list.findViewById(R.id.iv_join_cancel);
                iv_join_cancel.setOnClickListener(this);
                //添加加入提示监听和颜色
                joinWarn = search_room_list.findViewById(R.id.tv_join_warn);
                joinWarn.setTextColor(getApplicationContext().getResources().getColor(R.color.colorLogin1));

                joinDialog = new AlertDialog.Builder(UserInfoActivity.this)
                        .setView(search_room_list)
                        .create();
                break;
            case R.id.iv_join_cancel:
                joinDialog.cancel();
                break;
        }
    }

   /* public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ui_bt_create:
                create_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.in_anim));
                create_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.out_anim));

                this.initLimit();

                createDialog = new AlertDialog.Builder(this)
                        .setView(tl_chip_limit)
                        *//*.setPositiveButton("申请房间", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                HashMap<Object, Object> crrMap = new HashMap<>();
                                crrMap.put("reqType", "createRoomReq");
                                crrMap.put("userId", jsonObject.getString("userId"));
                                crrMap.put("upperChip", maxDefaultValue);
                                crrMap.put("lowerChip", minDefaultValue);
                                crrMap.put("userLimit", userLimit);

                                intent.putExtra("request", JSONObject.toJSON(crrMap).toString());
                                sendBroadcast(intent);
                            }
                        })
                        .setNegativeButton("取消", null)*//*
                        .create();
                createDialog.show();
                break;
            case R.id.ui_bt_join:
                AlertShow.dialog = ProgressDialog.show(this, null, "获取房间中...");

                join_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.in_anim));
                join_room.startAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.out_anim));

                Map<Object, Object> grlMap = new HashMap<>();
                grlMap.put("reqType", "getRoomListReq");
                grlMap.put("filterRoom", "");
                intent.putExtra("request", JSONObject.toJSON(grlMap).toString());
                sendBroadcast(intent);


                search_room_list = (SwipeRefreshLayout) UserInfoActivity.this.getLayoutInflater().inflate(R.layout.search_room_list, null);
                //添加加入提示监听和颜色
                joinWarn = search_room_list.findViewById(R.id.tv_join_warn);
                joinWarn.setTextColor(getApplicationContext().getResources().getColor(R.color.colorLogin1));

                joinDialog = new AlertDialog.Builder(UserInfoActivity.this)
                        .setView(search_room_list)
                        .create();
                break;
            *//*case R.id.ui_bt_exit:
                Map<String, Object> erMap = new HashMap<>();
                erMap.put("reqType", "exitReq");
                intent.putExtra("request", JSONObject.toJSON(erMap).toString());
                sendBroadcast(intent);
                musicIntent.putExtra("musicStatus", false);
                sendBroadcast(musicIntent);
                finish();
                break;
            case R.id.ui_tb_music:
                if (tb_music.isChecked()) {
                    musicIntent.putExtra("musicStatus", true);
                } else {
                    musicIntent.putExtra("musicStatus", false);
                }
                sendBroadcast(musicIntent);
                break;
            case R.id.bt_scratch_card:
                RelativeLayout relativeLayout = (RelativeLayout) this.getLayoutInflater().inflate(R.layout.scratch_card, null);
                ScratchSurFaceView scratch_card = relativeLayout.findViewById(R.id.scratchSurFaceView);
                scratch_card.licensing();
//                Button scratch = relativeLayout.findViewById(R.id.scratch);
                new AlertDialog.Builder(this)
                        .setTitle("刮奖")
                        .setView(relativeLayout)
                        .create()
                        .show();
//                scratch.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Log.e("aaa","bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
//                    }
//                });
                break;*//*
        }
    }*/

    public class UserInfoReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String respType = intent.getStringExtra("getRoom");

            /*if ("601".equals(respType) || "801".equals(respType)) {
                String seatId = intent.getStringExtra("seatId");
                Bundle data = new Bundle();
                data.putSerializable("userName", userName);
                data.putSerializable("seatId", seatId);
                Intent startActivity = new Intent(getApplicationContext(), UserRoomActivity.class);
                startActivity.putExtras(data);
                startActivity(startActivity);
            } else */
            if ("602".equals(respType)) {
                createWarn.setText("不可以创建多个房间");
            } else if ("701".equals(respType)) {//获取状态为未关闭的房间(!=0),及搜索房间
                roomList = intent.getStringExtra("roomList");
                List<RoomInfo> roomInfoList = JSONObject.parseArray(roomList, RoomInfo.class);
                if (roomInfoList.isEmpty()) {
                    joinWarn.setText("目前暂时没有房间");
                }
                getRoomList(roomInfoList);
            } else if ("802".equals(respType)) {
                joinWarn.setText("房间已满，请下拉刷新");
            }else if("603".equals(respType)){
                finish();
            }
        }

        private void getRoomList(final List<RoomInfo> roomInfoList) {

            RoomListAdapter roomListAdapter = new RoomListAdapter(UserInfoActivity.this, roomInfoList);
            search_room = search_room_list.findViewById(R.id.sv_search_room);
            room_list = search_room_list.findViewById(R.id.lv_room_list);
            room_list.setAdapter(roomListAdapter);

            search_room.setSubmitButtonEnabled(true);
            search_room.setQueryHint("查询房间名");
//            search_room.setIconified(false);

            search_room.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                Intent intentFilter = new Intent(CustomAction.SERVICE_ACTION);

                @Override
                public boolean onQueryTextSubmit(String s) {
                    Map<Object, Object> grlMap = new HashMap<>();
                    grlMap.put("reqType", "getRoomListReq");
                    grlMap.put("filterRoom", s);
                    intentFilter.putExtra("request", JSONObject.toJSON(grlMap).toString());
                    sendBroadcast(intentFilter);
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String s) {
                    Map<Object, Object> grlMap = new HashMap<>();
                    grlMap.put("reqType", "getRoomListReq");
                    if (TextUtils.isEmpty(s)) {
                        grlMap.put("filterRoom", "");
                    } else {
                        grlMap.put("filterRoom", s);
                    }
                    intentFilter.putExtra("request", JSONObject.toJSON(grlMap).toString());
                    sendBroadcast(intentFilter);
                    return true;
                }
            });

            //解决SwipeRefreshLayout和listView下拉冲突
            room_list.setOnScrollListener(new AbsListView.OnScrollListener() {

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                                     int visibleItemCount, int totalItemCount) {
                    boolean enable = false;
                    if (room_list != null && room_list.getChildCount() > 0) {
                        // check if the first item of the list is visible
                        boolean firstItemVisible = room_list.getFirstVisiblePosition() == 0;
                        // check if the top of the first item is visible
                        boolean topOfFirstItemVisible = room_list.getChildAt(0).getTop() == 0;
                        // enabling or disabling the refresh layout
                        enable = firstItemVisible && topOfFirstItemVisible;
                    }
                    search_room_list.setEnabled(enable);
                }
            });

            room_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Map<String, Object> joinMap = new HashMap<>();
                    joinMap.put("reqType", "joinRoomReq");
                    joinMap.put("roomId", roomInfoList.get(position).getRoomId());
                    joinMap.put("userId", userId);
                    Intent joinIntent = new Intent(CustomAction.SERVICE_ACTION);
                    joinIntent.putExtra("request", JSONObject.toJSON(joinMap).toString());
                    sendBroadcast(joinIntent);
//                    joinDialog.dismiss();关闭就看不了错误提示
                }
            });

            search_room_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    //清空搜索框文本内容
                    search_room.setQuery("", false);//如果submit=true，则调用onQueryTextSubmit方法，详细请看setQuery方法
                    joinWarn.setText("");
                    Map<String, Object> grlMap = new HashMap<>();
                    grlMap.put("reqType", "getRoomListReq");
                    grlMap.put("filterRoom", "");
                    Intent intentRefresh = new Intent(CustomAction.SERVICE_ACTION);
                    intentRefresh.putExtra("request", JSONObject.toJSON(grlMap).toString());
                    sendBroadcast(intentRefresh);
                }
            });

            if (AlertShow.dialog != null) {
                AlertShow.dialog.dismiss();
            }

            joinDialog.show();
            if (search_room_list.isRefreshing()) {
                search_room_list.setRefreshing(false);
            }
        }
    }

    private void initLimit() {
        //需要点击及加载，不然报错Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        tl_chip_limit = (LinearLayout) this.getLayoutInflater().inflate(R.layout.user_chip_limit, null);
        iv_create_cancel = tl_chip_limit.findViewById(R.id.iv_create_cancel);
        iv_create_cancel.setOnClickListener(this);
        bt_edit_room = tl_chip_limit.findViewById(R.id.bt_edit_room);
        createWarn = tl_chip_limit.findViewById(R.id.tv_create_warn);
        createWarn.setTextColor(getApplicationContext().getResources().getColor(R.color.colorLogin1));
        bt_edit_room.setOnClickListener(this);
        //加载tl_chip_limit后，要用tl_chip_limit找到id，不是当前找到id
        minDefaultValue = 1;
        maxDefaultValue = 10;
        userLimit = 5;
        upper_chip = tl_chip_limit.findViewById(R.id.np_upper_limit);
        upper_chip.setMinValue(10);
        upper_chip.setMaxValue(100);
        upper_chip.setValue(maxDefaultValue);

        upper_chip.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                maxDefaultValue = i1;
            }
        });

        lower_chip = tl_chip_limit.findViewById(R.id.np_lower_limit);
        lower_chip.setMinValue(1);
        lower_chip.setMaxValue(10);
        lower_chip.setValue(minDefaultValue);

        lower_chip.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                minDefaultValue = i1;
            }
        });

        user_limit = tl_chip_limit.findViewById(R.id.np_user_limit);
        user_limit.setMinValue(2);
        user_limit.setMaxValue(5);
        user_limit.setValue(userLimit);

        user_limit.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                userLimit = i1;
            }
        });
    }

}
